<?php
/***********************************************************
 * 在线升级
 * @作者 pcfcms <1131680521@qq.com>
 * @版权 广州市春风科技有限公司
 * @主页 http://www.pcfcms.com
 * @时间 2019年12月21日
***********************************************************/
namespace app\admin\controller;
use think\facade\Db;
use think\facade\Session;
use think\facade\Request;
use think\facade\Cache;
use app\admin\logic\UpdateLogic;
class Update extends Base
{
    public $popedom = '';
    public function initialize() {
        parent::initialize();
        $ctl_act = Request::controller().'/index';
        $this->popedom = appfile_popedom($ctl_act);
		$this->updatelogic = new UpdateLogic();
        @ini_set('memory_limit', '1024M'); // 设置内存大小
        @ini_set("max_execution_time", "0"); // 请求超时时间 0 为不限时
        @ini_set('default_socket_timeout', 3600);
    }

	// 主界面
    public function index()
    {
        if(!$this->popedom["list"]){
            return $this->errorNotice(config('params.auth_msg.list'),true,3,false);
        }
        return $this->fetch();
    }

    // 在线升级
    public function upmain()
    {
        if(!$this->popedom["list"]){
            return $this->errorNotice(config('params.auth_msg.list'),true,3,false);
        }
        $data = $this->updatelogic->OneKeyUpgrade(); //升级包消息
        if (1 <= intval($data['code'])) {
            $result = ['code' => $data['code'], 'msg' => $data['msg']];
            return $result; 
        } else {
            $code = 0;
            $msg = '升级异常，请第一时间联系技术支持，排查问题！';
            if (is_array($data)) {
                $code = $data['code'];
                $msg = $data['msg'];
            }
            $result = ['code' => $code, 'msg' => $msg];
            return $result; 
        }
    }

	// 检查是否有升级包
	public function check()
    {
        if(!$this->popedom["list"]){
            $result = ['code' => 0, 'msg' => "不可在线升级"];
            return $result; 
        }
        $allow_url_fopen = ini_get('allow_url_fopen');
        if (!$allow_url_fopen) {
            return ['code' => 0, 'msg' => "<font color='red'>请联系空间商（设置 php.ini 中参数 allow_url_fopen = 1）</font>"];
        }
		$upgradeMsg = $this->updatelogic->pcfcms_service(1);
		if($upgradeMsg['code'] > 0){
			$result = ['code' => 1, 'msg' => '检测成功', 'data' => $upgradeMsg];
			return $result; 				
		}else{
			$result = ['code' => 0, 'msg' => $upgradeMsg['msg']];
			return $result;			
		}
	}

    // 环境配置
    public function set()
    {
        if(!$this->popedom["list"]){
            return $this->errorNotice(config('params.auth_msg.list'),true,3,false);
        }
        if (Request::isPost()) {
            $post = input('param.');
            $status = isset($post['status']) ? $post['status'] :'0';
            $server = isset($post['server']) ? base64_encode($post['server']) :'';
			$testserver = base64_decode($server);
			if(substr($testserver,-1) != '/'){
				$testserver .= '/';// 强制添加斜杠后续
				$server = base64_encode($testserver);
			}
            $date = isset($post['date']) ? $post['date'] :'';
            $ip = isset($post['ip']) ? $post['ip'] :'';
			$onlyid = isset($post['onlyid']) ? $post['onlyid'] :'cGNmY21z';
            $uconfig["status"] = $status;
            $uconfig["server"] = $server;
            $uconfig["date"] = $date;
            $uconfig["ip"] = $ip;
            $uconfig["onlyid"] = $onlyid;
            foreach ($uconfig as $k=>$v){
                $newK = strtolower($k);
                $newArr = array('name'=>$newK,'value'=>trim($v),'update_time' => time(),);
                if(isset($newK)){
                    Db::name('update_config')->where(['name' => $newK])->save($newArr);
                }
            }
            $result = ['status' => true, 'msg' => "修改成功",'url' =>Request::baseFile().'/update/index' ];
            return $result;   
        }
        $uconfig = getupdateData('update');
		$uconfig['server'] = base64_decode($uconfig['server']);
        $this->assign("rs",$uconfig);
        return $this->fetch('update_set');
    }

    // 设置弹窗更新-不再提醒
    public function setPopupUpgrade()
    {
        $show_popup_upgrade = input('param.show_popup_upgrade/s', '1');
        tpCache('web', array('web_show_popup_upgrade'=>$show_popup_upgrade));
        respose(1);
    }

    // 检测目录权限、当前版本的数据库是否与官方一致
    public function check_authority()
    {
        $filelist = tpCache('system.system_upgrade_filelist');
        $filelist = base64_decode($filelist);
        $filelist = htmlspecialchars_decode($filelist);
        $filelist = explode('<br>', $filelist);
        $dirs = array();
        $i = -1;
        foreach($filelist as $filename){
            $tfilename = $filename;
            $curdir = $this->GetDirName($tfilename);
            if (empty($curdir)) {
                continue;
            }
            if( !isset($dirs[$curdir]) ){
                $dirs[$curdir] = $this->TestIsFileDir($curdir);
            }
            if($dirs[$curdir]['isdir'] == false){
                continue;
            }else{
                @tp_mkdir($curdir, 0777);
                $dirs[$curdir] = $this->TestIsFileDir($curdir);
            }
            $i++;
        }
        $is_pass = true;
        $msg = '检测通过';
        if($i > -1){
            $n = 0;
            $dirinfos = '';
            foreach($dirs as $curdir)
            {
                $dirinfos .= $curdir['name']."&nbsp;&nbsp;状态：";
                if ($curdir['writeable']) {
                    $dirinfos .= "[√正常]";
                } else {
                    $is_pass = false;
                    $n++;
                    $dirinfos .= "<font color='red'>[×不可写]</font>";
                }
                $dirinfos .= "<br/>";
            }
            $title = "本次升级需要在下面文件夹写入更新文件，已检测站点有 <font color='red'>{$n}</font> 处没有写入权限：<br/>";
            $title .= "<font color='red'>问题分析（如有问题，请咨询技术支持）：<br/>";
            $title .= "1、检查站点目录的用户组与所有者，禁止是 root ;<br/>";
            $title .= "2、检查站点目录的读写权限，一般权限值是 0755 ;<br/>";
            $title .= "</font>涉及更新目录列表如下：<br/>";
            $msg = $title . $dirinfos;
        }
        if (true == $is_pass) {
			$result = ['code' => 1, 'msg' => $msg];
			return json($result);
        } else {
			$result = ['code' => 0, 'msg' => $msg];
			return json($result);
        }
	}

    /**
     * 获取文件的目录路径
     * @param string $filename 文件路径+文件名
     */
    private function GetDirName($filename)
    {
        $dirname = preg_replace("#[\\\\\/]{1,}#", '/', $filename);
        $dirname = preg_replace("#([^\/]*)$#", '', $dirname);
        return $dirname;
    }

    /**
     * 测试目录路径是否有读写权限
     * @param string $dirname 文件目录路径
     */
    private function TestIsFileDir($dirname)
    {
        $dirs = array('name'=>'', 'isdir'=>false, 'writeable'=>false);
        $dirs['name'] =  $dirname;
        tp_mkdir($dirname);
        if(is_dir($dirname))
        {
            $dirs['isdir'] = true;
            $dirs['writeable'] = $this->TestWriteAble($dirname);
        }
        return $dirs;
    }

    /**
     * 测试目录路径是否有写入权限
     * @param string $d 目录路劲
     */
    private function TestWriteAble($d)
    {
        $tfile = '_pcfcms.txt';
        $fp = @fopen($d.$tfile,'w');
        if(!$fp) {
            return false;
        }else {
            fclose($fp);
            $rs = @unlink($d.$tfile);
            return true;
        }
    }

}